//
//  MineViewController.m
//  DanaKreditLoan
//
//  Created by ZhengChengFeng on 2024/10/18.
//

#import "MineViewController.h"
#import "MineModel.h"

#define kTabCell @"kTabCell"

@interface MineViewController ()

@property (nonatomic) MineModel *model;

@property (nonatomic) BOOL isOffsetY;

@end

@implementation MineViewController

- (CALayer *)colorFrameWidth:(CGFloat)width withHeight:(CGFloat)height withColorAry:(NSArray *)colorAry{
    CAGradientLayer *gradientLayer =  [CAGradientLayer layer];
    gradientLayer.frame = CGRectMake(0, 0, width, height);
    gradientLayer.startPoint = CGPointMake(0, 0);
    gradientLayer.endPoint = CGPointMake(0,1);
    gradientLayer.locations = @[@(0.0),@(1.0)];
    gradientLayer.colors = colorAry;
    return gradientLayer;
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    
    [self loadData];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:kTabCell];
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 40)];
    
}

- (void)loadData{
    
    NSString *versonStr = [NSString stringWithFormat:@"%@:%@",ASLocalizedString(@"Version"),kAppVersion];
    NSDictionary *dic3 = @{
        @"id":@"30",
        @"arrow":versonStr,
        @"btnImg":@"icon_mine9",
    };
    NSDictionary *dic4 = @{
        @"id":@"40",
        @"arrow":ASLocalizedString(@"Account Cancellation"),
        @"btnImg":@"icon_mine10",
    };
    NSDictionary *dic5 = @{
        @"id":@"50",
        @"arrow":ASLocalizedString(@"Go Out"),
        @"btnImg":@"icon_mine11",
    };
    
    
    
    [BoxLoadingHelper showBoxLoadingWithMessage:@"" onView:self.view withOriginY:0];
    
    NSMutableDictionary *muDic = @{
        @"behaved":@"behavedMine",
    }.mutableCopy;
    [HttpNetHelper getNetworkHelperForPath:kMineUrl parameter:muDic onCompleteSuccess:^(NSDictionary * _Nonnull responseDic) {
        [BoxLoadingHelper hideBoxLoadingFromView:self.view];
        if ([responseDic[@"pineapples"] integerValue] != kSuccessCode) {
            [BoxLoadingHelper showBoxWithMessage:esString(responseDic[@"shin"])];
            return;
        }
        [self.data removeAllObjects];
        
        NSDictionary *dic = responseDic[@"clip"];
        NSArray *pinAry = dic[@"islet"];
        
        NSMutableArray *muArr = [[NSMutableArray alloc] init];
        [muArr addObjectsFromArray:pinAry];
        [muArr addObject:dic3];
        [muArr addObject:dic4];
        [muArr addObject:dic5];
       
        
        
        self.data = [MineModel mj_objectArrayWithKeyValuesArray:muArr];
        
        [self initHeadView];
        
        [self.tableView reloadData];
        
    } onCompleteFailur:^(NSError * _Nonnull error) {
        [BoxLoadingHelper hideBoxLoadingFromView:self.view];
    } withIsForm:NO];
    
}



- (void)initHeadView{
    
    
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, DimensionBaseIphone6(88 + 168 + 114 + 20 + 215 + 20 + 88 + 10))];
    [headView.layer addSublayer:[self colorFrameWidth:kScreenWidth withHeight:headView.frame.size.height withColorAry:@[
        (__bridge id)[UIColor colorWithHexString:@"#FFFFFF"].CGColor,
        (__bridge id)[UIColor colorWithHexString:@"#F7F7F7"].CGColor,
    ]]];
    headView.userInteractionEnabled = YES;
    self.tableView.tableHeaderView = headView;
    
    UILabel *lab = [UILabel createLabel:[UIFont fontWithName:kFuturaMedium size:16] color:kBlackColor];
    lab.text = ASLocalizedString(@"Private Center");
    lab.textAlignment = 1;
    lab.frame = CGRectMake(0, DimensionBaseIphone6(44), kScreenWidth, DimensionBaseIphone6(44));
    [headView addSubview:lab];
    
    UIImageView *headImgV = [[UIImageView alloc] initWithFrame:CGRectMake((headView.width - DimensionBaseIphone6(94))/2, lab.bottom + DimensionBaseIphone6(20), DimensionBaseIphone6(94), DimensionBaseIphone6(94))];
    headImgV.image = [UIImage imageNamed:@"icon_mine1"];
    [headView addSubview:headImgV];
    
    UILabel *phoneLab = [UILabel createLabel:[UIFont fontWithName:kFutura size:20] color:kBlackColor];
    NSString *phoneStr = [NSString starsReplacedOfString:esString([[NSUserDefaults standardUserDefaults] valueForKey:kUserTelPhone]) withinRange:NSMakeRange(2, 4)];
    phoneLab.text = [NSString stringWithFormat:@"%@",esString(phoneStr)];
    phoneLab.frame = CGRectMake(0, headImgV.bottom  + DimensionBaseIphone6(8), kScreenWidth, DimensionBaseIphone6(30));
    [headView addSubview:phoneLab];
    phoneLab.textAlignment = 1;
    
    UIImageView *iconImgV1 = [[UIImageView alloc] initWithFrame:CGRectMake(15, DimensionBaseIphone6(88 + 168), kScreenWidth - 30, DimensionBaseIphone6(114))];
    iconImgV1.image = [UIImage imageNamed:@"icon_mine2"];
    [headView addSubview:iconImgV1];
    iconImgV1.userInteractionEnabled = YES;
    
    CGFloat btnW = DimensionBaseIphone6(46);
    CGFloat btnH = btnW;
    CGFloat btnFix = (iconImgV1.width - 40 - 4*btnW)/3;
    NSArray *titleArr = @[ASLocalizedString(@"All"),ASLocalizedString(@"Applying"),ASLocalizedString(@"Repayment"),ASLocalizedString(@"Finish")];
    NSArray *imgArr = @[@"icon_mine3",@"icon_mine4",@"icon_mine5",@"icon_mine6"];
    for (int i=0; i<titleArr.count; i++) {
    
        UIButton *btn = [[UIButton alloc] init];
        btn.frame = CGRectMake(20 + btnW*i + btnFix*i, DimensionBaseIphone6(24), btnW, btnH);
        [iconImgV1 addSubview:btn];
        btn.tag = i+1;
        [btn addTarget:self action:@selector(clickBtn1:) forControlEvents:UIControlEventTouchUpInside];
        
        [btn setImage:[UIImage imageNamed:imgArr[i]] forState:UIControlStateNormal];
        [btn setImage:[UIImage imageNamed:imgArr[i]] forState:UIControlStateSelected];
        [btn setImage:[UIImage imageNamed:imgArr[i]] forState:UIControlStateHighlighted];
        

        UILabel *lab = [UILabel createLabel:[UIFont fontWithName:kFuturaMedium size:14] color:kWhiteColor];
        lab.text = titleArr[i];
        lab.textAlignment = 1;
        
        lab.frame = CGRectMake(0, btn.bottom, btn.width + 30, DimensionBaseIphone6(25));
        lab.centerX = btn.centerX;
        [iconImgV1 addSubview:lab];
        lab.adjustsFontSizeToFitWidth = YES;
        
        
    }
    
    CGFloat fixHeight = 0;
    if (self.data.count > 6) {
        fixHeight = 85;
    }
    
    UIView *whiteView = [[UIView alloc] initWithFrame:CGRectMake(15, iconImgV1.bottom + DimensionBaseIphone6(20), kScreenWidth - 30, DimensionBaseIphone6(215 + fixHeight))];
    whiteView.backgroundColor = [UIColor whiteColor];
    [headView addSubview:whiteView];
    whiteView.layer.cornerRadius = 14;
    whiteView.layer.masksToBounds = YES;
    
    UILabel *featureLab = [UILabel createLabel:[UIFont fontWithName:kFuturaBold size:13] color:kBlackColor];
    [whiteView addSubview:featureLab];
    featureLab.frame = CGRectMake(20, DimensionBaseIphone6(10), 200, DimensionBaseIphone6(22));
    featureLab.text = ASLocalizedString(@"More Features");
    
    UIImageView *ic = [[UIImageView alloc] initWithFrame:CGRectMake(whiteView.width - DimensionBaseIphone6(97), 0, DimensionBaseIphone6(97), DimensionBaseIphone6(100))];
    ic.image = [UIImage imageNamed:@"icon_mine12"];
    [whiteView addSubview:ic];
    
    CGFloat btnMoreW = DimensionBaseIphone6(26);
    
    CGFloat btnMoreH = btnMoreW;
    
    CGFloat kBtnFix = (whiteView.frame.size.width - 54*2 - 3*btnMoreW)/2;
    
    for (int i=0; i<self.data.count; i++) {
        
        self.model = self.data[i];
        
        UIImageView *imgV = [[UIImageView alloc] init];
        imgV.frame = CGRectMake(54+btnMoreW*(i%3) + kBtnFix*(i%3), featureLab.bottom + DimensionBaseIphone6(30) + btnMoreH*(i/3) + DimensionBaseIphone6(60)*(i/3), btnMoreW, btnMoreH);
        [whiteView addSubview:imgV];
        imgV.tag = i;
        imgV.userInteractionEnabled = YES;
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickMoreBtn:)];
        [imgV addGestureRecognizer:tap];
        
        
        
        if (PMStringIsEmpty(self.model.btnImg)) {
            [imgV sd_setImageWithURL:[NSURL URLWithString:self.model.missionaries]];
        } else {
            imgV.image = [UIImage imageNamed:esString(self.model.btnImg)];
        }
        
        
        UILabel *lab = [UILabel createLabel:[UIFont fontWithName:kFuturaMedium size:12] color:kBlackColor];
        lab.text = esString(self.model.arrow);
        lab.textAlignment = 1;
        lab.frame = CGRectMake(0, imgV.bottom + DimensionBaseIphone6(5), whiteView.width/3, DimensionBaseIphone6(20));
        lab.centerX = imgV.centerX;
        [whiteView addSubview:lab];
        lab.adjustsFontSizeToFitWidth = YES;
        
        
    }
    
    NSString *imgStr = @"icon_mine13";
    if ([CurrentUser mine].isYNLanguage) {
        imgStr = @"icon_mine13-yn";
    }
    UIImageView *botImgV = [[UIImageView alloc] initWithFrame:CGRectMake(15, whiteView.bottom + DimensionBaseIphone6(20), kScreenWidth - 30, DimensionBaseIphone6(88))];
    [headView addSubview:botImgV];
    botImgV.image = [UIImage imageNamed:imgStr];
    
    botImgV.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickBotomTap)];
    [botImgV addGestureRecognizer:tap];
    
    [self.tableView reloadData];
    
}

- (void)clickBtn1:(UIButton *)btn{
    
    
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:kNeedToRefreshOrderListPage];
    [[NSUserDefaults standardUserDefaults] setInteger:btn.tag - 1 forKey:kRecordBtnNum];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    NSInteger inter = 2;
    NSString *str = @"3";
    if ([CurrentUser mine].isYNLanguage) {
        inter = 1;
        str = @"2";
    }
    
    [self.tabBarController setSelectedIndex:inter];
    [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationTabBarNum object:nil userInfo:@{@"index":str}];
}

- (void)clickMoreBtn:(UITapGestureRecognizer *)tap{
    UIImageView *tapV = (UIImageView *)tap.view;
    self.model = self.data[tapV.tag];
    
    
    if ([self.model.ID integerValue] == 20) {
        [[DKCore sharedDKCore] jumpToControllerWithUrlString:kAgreementUrl];
    }
    else if ([self.model.ID integerValue] == 30) {
        [BoxLoadingHelper showBoxWithMessage:esString(self.model.arrow)];
    }
    else if ([self.model.ID integerValue] == 40) {
        AlertGoOutView *alertV = [[AlertGoOutView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) withTitleStr:ASLocalizedString(@"Account Cancellation") withDescStr:ASLocalizedString(@"AccountCancle") withCancelStr:ASLocalizedString(@"Cancel") withSureStr:ASLocalizedString(@"Delete Account") withIsAccountCancel:YES];
        [[UIApplication sharedApplication].keyWindow addSubview:alertV];
        alertV.clickSureBlock = ^{
            [BoxLoadingHelper showBoxLoadingWithMessage:@""];
            NSMutableDictionary *muDic = @{
                @"talking":@"talkingClearAcc",
            }.mutableCopy;
            [HttpNetHelper getNetworkHelperForPath:kClearAccountUrl parameter:muDic onCompleteSuccess:^(NSDictionary * _Nonnull responseDic) {
                [BoxLoadingHelper hideBoxLoading];
                if ([responseDic[@"pineapples"] integerValue] != kSuccessCode) {
                    [BoxLoadingHelper showBoxWithMessage:esString(responseDic[@"shin"])];
                    return;
                }
                [CurrentUser logoutControllerWithIsTokenExpire:NO];
                
            } onCompleteFailur:^(NSError * _Nonnull error) {
                [BoxLoadingHelper hideBoxLoading];
            } withIsForm:NO];
        };
    }
    else if ([self.model.ID integerValue] == 50) {
        AlertGoOutView *alertV = [[AlertGoOutView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) withTitleStr:ASLocalizedString(@"Go Out") withDescStr:ASLocalizedString(@"GoOutTips") withCancelStr:ASLocalizedString(@"Cancel") withSureStr:ASLocalizedString(@"Go Out") withIsAccountCancel:NO];
        [[UIApplication sharedApplication].keyWindow addSubview:alertV];
        alertV.clickSureBlock = ^{
            [BoxLoadingHelper showBoxLoadingWithMessage:@""];
            NSMutableDictionary *muDic = @{
                @"conversation":@"confusedLogout",
                @"confused":@"confusedLogout",
            }.mutableCopy;
            [HttpNetHelper getNetworkHelperForPath:kLogoutUrl parameter:muDic onCompleteSuccess:^(NSDictionary * _Nonnull responseDic) {
                [BoxLoadingHelper hideBoxLoading];
                if ([responseDic[@"pineapples"] integerValue] != kSuccessCode) {
                    [BoxLoadingHelper showBoxWithMessage:esString(responseDic[@"shin"])];
                    return;
                }
                [CurrentUser logoutControllerWithIsTokenExpire:NO];
                
            } onCompleteFailur:^(NSError * _Nonnull error) {
                [BoxLoadingHelper hideBoxLoading];
            } withIsForm:NO];
        };
            
    }
    else{
        [[DKCore sharedDKCore] jumpToControllerWithUrlString:esString(self.model.justified)];
    }
}

- (void)clickBotomTap{
    [self.tabBarController setSelectedIndex:0];
    [[NSNotificationCenter defaultCenter] postNotificationName:kNotificationTabBarNum object:nil userInfo:@{@"index":@"1"}];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 0.0001;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:kTabCell];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGFloat offset_Y = scrollView.contentOffset.y;
    if (offset_Y < 0) {
        if (offset_Y < - kNavigationBarHeight) {
            self.isOffsetY = YES;
        }
    }else{
        if (self.isOffsetY) {
            self.isOffsetY = NO;
            [self loadData];
        }
    }
}


@end
